<template>
  <div>
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option
            v-for="item in employeeList"
            :key="item.id"
            :value="item.username"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="$emit('close')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartmentsDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },

  data() {
    const validCode = (rule, value, callback) => {
      // 找到全部的编码
      let existCodeList = this.originList.map(item => item.code)
      if (this.isEdit) {
        // 利用filter方法，过滤掉相同的id的数据。获取不同id里面的数据，在用map方法获取编码
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existCodeList.includes(value)) {
        callback(new Error(`编码:${value} 已经存在`))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      let existNameLiset = this.originList.filter(item => item.pid === this.id)
      console.log(existNameLiset, '找到子部门')
      if (this.isEdit) {
        const curDepartment = this.originList.find(item => item.id === this.id)
        console.log(curDepartment, '当前正在编辑的对象')
        const brothers = this.originList.filter(item => item.pid === curDepartment.pid)
        console.log(brothers, '找到所有兄弟部门，包括自己')
        existNameLiset = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      if (existNameLiset.includes(value)) {
        callback(new Error(`部门名称:${value} 已存在`))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        code: '',
        introduce: '',
        manager: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ]
      },
      employeeList: []
    }
  },
  // 解决数据不更新
  watch: {
    'id': {
      deep: true,
      immediate: true,
      handler: function(nweVal, oldVal) {
        this.lodDepartmentsDetail()
      }
    }
  },
  created() {
    this.lodEmployeeSimple()
    // isEdit等于true 是编辑调用函数发送请求获取全部数据
    if (this.isEdit) {
      this.lodDepartmentsDetail()
    }
  },
  methods: {
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    hSubmit() {
      // 兜底效验
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
          // console.log(this.isEdit)
        }
      })
    },
    // 编辑
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // console.log(res)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取全部数据数据回显
    async lodDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        // console.log(res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 添加
    async doAdd() {
      try {
        const res = await addDepartments({ ...this.form, pid: this.id })
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        // console.log(res)
        // 关闭弹层重新渲染页面
        this.$emit('success')
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 获取员工基本信息
    async lodEmployeeSimple() {
      try {
        const res = await getEmployeeSimple()
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.employeeList = res.data
        // console.log(res, '获取员工基本信息')
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>

